var center = new ol.proj.fromLonLat([106.83854835625208, 29.714712949499628], 'EPSG:3857')

// 标绘模式状态
let markModeEnabled = false

// 创建地图
var map = new ol.Map({
    controls: ol.control.defaults.defaults({
        zoom: false,
    }).extend([
    // 比例尺
        new ol.control.ScaleLine()
    ]),
    view: new ol.View({
        center: center, // 中心点, 填的是经纬度
        zoom: 16, // 地图默认缩放级别
        maxZoom: 19, // 地图最大缩放级别
        minZoom: 13, // 地图最小缩放级别
    }),
    target: 'map', // 地图容器id
})

const dblClickInteraction = map.getInteractions()
    .getArray()
    .find(interaction => {
        return interaction instanceof ol.interaction.DoubleClickZoom;
    });
map.removeInteraction(dblClickInteraction);

// 创建一个使用离线地图瓦片的图层
var offlineMapLayer = new ol.layer.Tile({
    source: new ol.source.XYZ({
        // url: '../../../../bzapp/WebGIS/tiles/{z}/{x}/{y}.png'
        url: 'file:///data/storage/el1/bundle/bzapp/WebGIS/tiles/{z}/{x}/{y}.png'
    })
});
map.addLayer(offlineMapLayer);

// 用于显示绘制区域的图层
var markerLayer = new ol.layer.Vector({
    source: new ol.source.Vector()
});
map.addLayer(markerLayer);

// 默认不开启地图点击事件
let mapClickEnabled = true

// 鼠标双击事件
map.on('dblclick', () => {
    console.log('dblclick')
})

// 添加地图点击事件监听器
map.on('click', function (event) {
    if (mapClickEnabled) {
        console.log('click')
        const coordinate = event.coordinate;
        const lonLat = ol.proj.toLonLat(coordinate);
        lonLat.push(generateUUID());
        callArsTSMapClick(lonLat);
        //drawPoint(lonLat[0], lonLat[1], lonLat[2]);
    }
});

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
};

function drawPoint(lon, lat, id) {
    // 绘制点
    const coordinate = ol.proj.fromLonLat([lon, lat])

    const pointGeometry = new ol.geom.Point(coordinate);
    const pointFeature = new ol.Feature(pointGeometry)
    pointFeature.setStyle(new ol.style.Style({
        image: new ol.style.Icon({
            anchor: [0.5, 0.5], // 图标的锚点位置，0.5表示水平居中，1表示垂直底部对齐
            scale: 0.3, // 图标缩放比例
            // src: './image/point.png'
            src: './image/friendly_marker.png'
        })
    }))
    pointFeature.setId(id)
    map.getLayers().item(1).getSource().addFeature(pointFeature)
}

function deletePoint(id) {
    // 删除点
    const pointFeature = map.getLayers().item(1).getSource().getFeatureById(id)
    webInterfaceObj.toString(pointFeature);

    map.getLayers().item(1).getSource().removeFeature(pointFeature)
}

function drawLine(lineLonLatStr) {
    webInterfaceObj.toString(lineLonLatStr);
    let lineLonLats = JSON.parse(lineLonLatStr);
    let lineCoordinates = new Array();
    for (var i = 0; i < lineLonLats.length; i++) {
        var coordinate = ol.proj.fromLonLat(lineLonLats[i]);
        lineCoordinates.push(coordinate);
    }

    // 绘制路径
    if (lineCoordinates.length >= 2) {
        const lineGeometry = new ol.geom.LineString(lineCoordinates);
        lineFeature = new ol.Feature(lineGeometry);
        lineFeature.setStyle(new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'blue',
                width: 1,
            }),
        }));
        map.getLayers().item(1).getSource().addFeature(lineFeature);
    }
}

function drawPolygon(polygonLonLatStr) {
    webInterfaceObj.toString(polygonLonLatStr);
    let polygonLonLats = JSON.parse(polygonLonLatStr);
    let polygonCoordinates = new Array();
    let firstCoordinate = null;
    for (var i = 0; i < polygonLonLats.length; i++) {
        var coordinate = ol.proj.fromLonLat(polygonLonLats[i]);
        if (i == 0) {
            firstCoordinate = coordinate;
        }
        polygonCoordinates.push(coordinate);
    }
    polygonCoordinates.push(firstCoordinate);

    // 绘制多边形
    if (polygonCoordinates.length >= 4) {
        const polygonGeometry = new ol.geom.Polygon([polygonCoordinates]);
        polygonFeature = new ol.Feature(polygonGeometry);
        polygonFeature.setStyle(new ol.style.Style({
            fill: new ol.style.Fill({
                color: [211, 211, 211, 0.5],
            }),
            stroke: new ol.style.Stroke({
                color: 'brown',
                width: 1,
            }),
        }))
        map.getLayers().item(1).getSource().addFeature(polygonFeature);
    }
}

function enableMapClick() {
    mapClickEnabled = true;
    webInterfaceObj.toString(mapClickEnabled);
}

function disableMapClick() {
    mapClickEnabled = false;
    webInterfaceObj.toString(mapClickEnabled);
}

function clearMarker() {
    map.getLayers().item(1).getSource().clear();
}

function callArsTSMapClick(lonLat) {
    webInterfaceObj.onMapClick(lonLat[2], lonLat[0], lonLat[1]);
}

// Native代理准备就绪回调
function onNativeProxyReady() {
    console.log('Native proxy is ready')
}
// 地图点击事件
function onMapClick(event) {
    if (markModeEnabled) {
        const markerInfo = {
            lng: event.lnglat.lng,
            lat: event.lnglat.lat,
            icon: './image/friendly_marker.png'
        }

        // 调用Native方法
        if (window.webInterfaceObj) {
            window.webInterfaceObj.addMarker(JSON.stringify(markerInfo))
        }
    }
}

// 切换标绘模式
function toggleMarkMode(status) {
    markModeEnabled = status

    // 调用Native方法
    if (window.webInterfaceObj) {
        window.webInterfaceObj.toggleMarkMode(status)
    }
}
// 定义marker图标类型  
const MARKER_TYPES = {
    ENEMY: {
        name: '敌方',
        icon: './image/enemy_marker.png',
    },
    FRIENDLY: {
        name: '我方',
        icon: './image/friendly_marker.png'
    },
    NEUTRAL: {
        name: '中立',
        icon: './image/neutral_marker.png'
    }
}


// 在页面加载时调用一次  
function initMarkerInteractions() {
    // 创建一个全局的 Overlay 对象
    window.markerPopupOverlay = new ol.Overlay({
        element: document.createElement('div'),
        positioning: 'bottom-center',
        stopEvent: true,
        insertFirst: false
    });
    map.addOverlay(window.markerPopupOverlay);

    // 移除之前的点击事件监听（避免重复绑定）
    map.un('click', markerClickHandler);
    map.on('click', markerClickHandler);
}

// 单独的点击事件处理函数  
function markerClickHandler(evt) {
    // 1. 清除之前的弹出框
    const overlay = window.markerPopupOverlay;
    const popupElement = overlay.getElement();
    popupElement.innerHTML = '';

    // 2. 检查点击位置是否有点要素
    const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
        // 只返回点类型的要素
        return feature.getGeometry().getType() === 'Point' ? feature : null;
    });

    // 3. 如果点击了已存在的Marker
    if (feature) {
        // 获取Marker的坐标
        const coordinates = feature.getGeometry().getCoordinates();

        // 创建并填充弹出框内容
        popupElement.innerHTML = createMarkerPopupHTML(feature);

        // 设置弹出框位置
        overlay.setPosition(coordinates);

        // 绑定弹出框的交互事件
        bindMarkerPopupEvents(feature, overlay);
    }
    // 4. 如果处于标记模式
    else if (markModeEnabled) {
        // 获取点击的地图坐标
        const coordinate = evt.coordinate;

        // 转换为经纬度
        const lonLat = ol.proj.toLonLat(coordinate);

        // 生成唯一标识符
        const markerId = generateUUID();

        // 在地图上绘制点
        drawPoint(lonLat[0], lonLat[1], markerId);

        // 通知Native端添加Marker
        if (window.webInterfaceObj) {
            window.webInterfaceObj.onMapClick(markerId, lonLat[0], lonLat[1]);
        }
    }
}

// 修改保存事件处理  
function bindMarkerPopupEvents(feature, overlay) {
    const saveBtn = document.getElementById('saveMarkerBtn');
    const deleteBtn = document.getElementById('deleteMarkerBtn');
    const typeSelect = document.getElementById('markerTypeSelect');
    const longitudeInput = document.getElementById('markerLongitude');
    const latitudeInput = document.getElementById('markerLatitude');
    const elevationInput = document.getElementById('markerElevation');
    const equipmentTypeSelect = document.getElementById('equipmentTypeSelect');
    const descriptionInput = document.getElementById('markerDescription');

    saveBtn.onclick = () => {
        const newType = typeSelect.value;
        const newLongitude = parseFloat(longitudeInput.value);
        const newLatitude = parseFloat(latitudeInput.value);
        const newElevation = parseFloat(elevationInput.value);
        const newEquipmentType = equipmentTypeSelect.value;
        const newDescription = descriptionInput.value;

        // 更新坐标
        const newCoordinate = ol.proj.fromLonLat([newLongitude, newLatitude]);
        feature.getGeometry().setCoordinates(newCoordinate);

        // 更新Marker数据和样式
        const markerData = {
            type: newType,
            longitude: newLongitude,
            latitude: newLatitude,
            elevation: newElevation,
            equipmentType: newEquipmentType,
            description: newDescription
        };

        feature.set('markerData', markerData);

        // 更新Marker图标
        feature.setStyle(new ol.style.Style({
            image: new ol.style.Icon({
                anchor: [0.5, 0.5],
                scale: 0.3,
                src: MARKER_TYPES[newType].icon
            })
        }));

        // 通知Native更新Marker
        if (window.webInterfaceObj) {
            window.webInterfaceObj.onMapClick(
                feature.getId(),
                newLongitude,
                newLatitude,
                JSON.stringify(markerData)
            );
        }

        overlay.setPosition(undefined); // 关闭弹出框
    };

    deleteBtn.onclick = () => {
        // 删除Marker
        map.getLayers().item(1).getSource().removeFeature(feature);
        overlay.setPosition(undefined);
    };
}
// 创建Marker弹出框的HTML模板  
function createMarkerPopupHTML(feature) {
    const markerData = feature.get('markerData') || {}
    const coordinates = ol.proj.toLonLat(feature.getGeometry().getCoordinates());

    return `
    <div class="marker-popup">
        <div class="popup-section">
            <label>标记类型:</label>
            <select id="markerTypeSelect">
                ${Object.entries(MARKER_TYPES).map(([key, type]) =>
    `<option value="${key}" ${markerData.type === key ? 'selected' : ''}>
                        ${type.name}
                    </option>`
    ).join('')}
            </select>
        </div>

        <div class="popup-section">
            <label>坐&nbsp;&nbsp;&nbsp;标:</label>
            <div class="coordinate-input">
                <input
                    type="text"
                    id="markerLongitude"
                    value="${coordinates[0].toFixed(6)}"
                    placeholder="经度"
                >
                <input
                    type="text"
                    id="markerLatitude"
                    value="${coordinates[1].toFixed(6)}"
                    placeholder="纬度"
                >
            </div>
        </div>

        <div class="popup-section elevation-input">
            <label>高&nbsp;&nbsp;&nbsp;程:</label>
            <input
                type="number"
                id="markerElevation"
                value="${markerData.elevation || ''}"
                placeholder="输入高程"
            >
        </div>

        <div class="popup-section">
            <label>装备类型:</label>
            <select id="equipmentTypeSelect">
                ${['坦克', '战斗人员', '工事', '指挥所', '无人机'].map((type) =>
    `<option value="${type}" ${markerData.equipmentType === type ? 'selected' : ''}>
                        ${type}
                    </option>`
    ).join('')}
            </select>
        </div>

        <div class="popup-section">
            <label>描&nbsp;&nbsp;&nbsp;述:</label>
            <input
                type="text"
                id="markerDescription"
                value="${markerData.description || ''}"
                placeholder="输入描述"
            >
        </div>

        <div class="popup-actions">
            <button id="saveMarkerBtn">保存</button>
            <button id="deleteMarkerBtn">删除</button>
        </div>
    </div>
    `;
}


// 页面加载时初始化  
initMarkerInteractions();